/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okex.open.api.config.APIConfiguration;
import com.okex.open.api.customize.util.ApiOkxUtil;
import com.okex.open.api.enums.I18nEnum;
import com.okex.open.api.service.account.AccountAPIService;
import com.okex.open.api.service.account.impl.AccountAPIServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.exception.DuckweedException;
import com.pig4cloud.pigx.common.customize.mysql.utils.MysqlUtil;
import com.pig4cloud.pigx.common.customize.redis.constants.RedisKeyEnum;
import com.pig4cloud.pigx.common.customize.redis.utils.RedisUtils;
import com.pig4cloud.pigx.common.customize.security.utils.SecurityUtil;
import com.pig4cloud.pigx.common.customize.utils.id.IdWorker;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.system.constant.SystemPlatformConstant;
import com.pig4cloud.pigx.user.entity.UserApi;
import com.pig4cloud.pigx.user.mapper.UserApiMapper;
import com.pig4cloud.pigx.user.service.UserApiService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 用户 api 表
 *
 * @author pigx code generator
 * @date 2022-11-29 17:24:47
 */
@Service
@AllArgsConstructor
public class UserApiServiceImpl extends ServiceImpl<UserApiMapper, UserApi> implements UserApiService {

    private final IdWorker idWorker;

    private final RedisUtils redisUtils;

    private final MysqlUtil mysqlUtil;


    @Override
    public R<String> userBindingApi(UserApi api) {
        try {
            // api参数必填校验
            if (api.getPlatformId() == null) {
                throw new DuckweedException(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED.getCode(), "平台不可为空");
            }
            // 查询用户
            PigxUser user = SecurityUtil.getLoginUser();
            if (user == null) {
                throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
            }
            // 同平台一个用户只能绑定一个API 不可重复绑定
            Long count = baseMapper.selectCount(new QueryWrapper<UserApi>() {{
                eq("user_id", user.getId());
                eq("platform_id", api.getPlatformId());
            }});
            if (count > 0) {
                throw new DuckweedException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "同平台不可重复绑定API");
            }
            // api参数必填校验
            if (api.getApiKey() == null || api.getApiKey().isEmpty()) {
                throw new DuckweedException(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED.getCode(), "apiKey不可为空");
            }
            if (api.getSecretKey() == null || api.getSecretKey().isEmpty()) {
                throw new DuckweedException(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED.getCode(), "secretKey不可为空");
            }
            if (api.getPassword() == null || api.getPassword().isEmpty()) {
                throw new DuckweedException(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED.getCode(), "密码不可为空");
            }

            api.setUserId(user.getId());
            api.setId(idWorker.nextId());
            // 开启事务
            mysqlUtil.startLocalTx();
            // 插入
            baseMapper.insert(api);
            // 尝试获取用户余额 判断是否为有效的API
            if (api.getPlatformId().equals(SystemPlatformConstant.OKX)) {
                try {
                    getOkxBalance(api);
                } catch (Exception e) {
                    throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED.getCode(), "API授权失败,无法获取欧易平台余额,请检查API信息是否填写正确!");
                }
            }

            // 持久化到redis
            redisUtils.flushPersistentCache(RedisKeyEnum.USER_API, api.getUserId() + "_" + api.getPlatformId(), api);
            mysqlUtil.commitLocalTx();
            return R.ok("绑定成功");
        } catch (DuckweedException e) {
            mysqlUtil.rollbackLocalTx();
            throw e;
        } catch (Exception e) {
            mysqlUtil.rollbackLocalTx();
            throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
        }
    }

    /**
     * 尝试获取OKX余额
     */
    private void getOkxBalance(UserApi api) throws Exception {
        // 获取余额校验是否绑定成功
        APIConfiguration configuration = new APIConfiguration();
        configuration.setEndpoint("https://www.okex.com/");
        configuration.setApiKey(api.getApiKey());
        configuration.setSecretKey(api.getSecretKey());
        configuration.setPassphrase(api.getPassword());
        configuration.setPrint(true);
        configuration.setI18n(I18nEnum.ENGLISH);
        AccountAPIService service = new AccountAPIServiceImpl(configuration);
        // 请求ok并校验结果
        JSONObject result = service.getBalance("USDT");
        ApiOkxUtil.isSuccess(result);
        JSONArray data = result.getJSONArray("data");
        JSONArray details = data.getJSONObject(0).getJSONArray("details");
        JSONObject detail = details.getJSONObject(0);
        // 可用额度
        BigDecimal availableBalance = detail.getBigDecimal("availEq");
        if (Objects.isNull(availableBalance)) {
            throw new Exception();
        }
    }

    /**
     * 解除绑定
     *
     * @param id 主键
     * @return r
     */
    @Override
    public R<String> relieveBindingApi(Long id) {
        try {
            // 查询用户
            PigxUser user = SecurityUtil.getLoginUser();
            if (user == null) {
                throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
            }
            UserApi api = baseMapper.selectById(id);
            if (api == null) {
                throw new DuckweedException(AbnormalEnum.MSG.UNKNOWN_ORDER_COMPOSITION.getCode(), "未查询到此api");
            }
            if (!api.getUserId().equals(user.getId())) {
                throw new DuckweedException(AbnormalEnum.MSG.UNKNOWN_ORDER_COMPOSITION.getCode(), "删除的api非所属当前登陆人持有");
            }
            baseMapper.deleteById(id);
            redisUtils.delPersistentCache(RedisKeyEnum.USER_API, api.getUserId() + api.getPlatformId());
            return R.ok("解除绑定成功");
        } catch (DuckweedException e) {
            throw e;
        } catch (Exception e) {
            throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
        }
    }

    /**
     * 获取用户绑定的api列表
     *
     * @return list
     */
    @Override
    public R<List<UserApi>> getApiList() {
        try {
            PigxUser user = SecurityUtil.getLoginUser();
            if (user == null) {
                throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
            }
            List<UserApi> apis = baseMapper.selectList(new QueryWrapper<UserApi>() {{
                eq("user_id", user.getId());
                select("id", "api_key", "secret_key", "platform_id");
            }});
            return R.ok(apis);
        } catch (DuckweedException e) {
            throw e;
        } catch (Exception e) {
            throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
        }
    }

    /**
     * 编辑api
     *
     * @param userApi api
     * @return r
     */
    @Override
    public R<String> updateApi(UserApi userApi) {
        try {
            PigxUser user = SecurityUtil.getLoginUser();
            if (user == null) {
                throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
            }
            if (!userApi.getUserId().equals(user.getId())) {
                throw new DuckweedException(AbnormalEnum.MSG.UNKNOWN_ORDER_COMPOSITION.getCode(), "修改的api非所属当前登陆人持有");
            }
            baseMapper.updateById(userApi);
            return R.ok("修改成功");
        } catch (DuckweedException e) {
            throw e;
        } catch (Exception e) {
            throw new DuckweedException(AbnormalEnum.MSG.DISCONNECTED);
        }
    }

}
